package com.amin.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

import org.junit.Test;

public class ChannelDemo {

	@Test
	public void test1() throws Exception {
		String info[] = { "MLDN", "MLDNJAVA", "www.mldn.cn", "www.mldnjava.cn", "李兴华", "lixinghua" };
		File file = new File("d:" + File.separator + "out.txt");
		FileOutputStream output = new FileOutputStream(file);
		FileChannel fout = output.getChannel(); // 得到输出的通道
		ByteBuffer buf = ByteBuffer.allocate(1024);
		for (int i = 0; i < info.length; i++) {
			buf.put(info[i].getBytes()); // 字符串变为字节数组放进缓冲区之中
		}
		buf.flip();
		fout.write(buf); // 输出缓冲区的内容
		fout.close();
		output.close();
	}

	@Test
	public void test2() throws Exception {
		File file1 = new File("d:" + File.separator + "note.txt");
		File file2 = new File("d:" + File.separator + "outnote.txt");
		FileInputStream input = null;
		FileOutputStream output = null;
		output = new FileOutputStream(file2);
		input = new FileInputStream(file1);
		FileChannel fout = null; // 声明FileChannel对象
		FileChannel fin = null; // 定义输入的通道
		fout = output.getChannel(); // 得到输出的通道
		fin = input.getChannel(); // 得到输入的通道
		ByteBuffer buf = ByteBuffer.allocate(1024);

		int temp = 0;
		while ((temp = fin.read(buf)) != -1) {
			buf.flip();
			fout.write(buf);
			buf.clear(); // 清空缓冲区,所有的状态变量的位置恢复到原点
		}
		fin.close();
		fout.close();
		input.close();
		output.close();
	}

	@Test
	public void test3() throws Exception {
		int ports[] = { 8000, 8001, 8002, 8003, 8005, 8006 }; // 表示五个监听端口
		Selector selector = Selector.open(); // 通过open()方法找到Selector
		for (int i = 0; i < ports.length; i++) {
			ServerSocketChannel initSer = null;
			initSer = ServerSocketChannel.open(); // 打开服务器的通道
			initSer.configureBlocking(false); // 服务器配置为非阻塞
			ServerSocket initSock = initSer.socket();
			InetSocketAddress address = null;
			address = new InetSocketAddress(ports[i]); // 实例化绑定地址
			initSock.bind(address); // 进行服务的绑定
			initSer.register(selector, SelectionKey.OP_ACCEPT); // 等待连接
			System.out.println("服务器运行，在" + ports[i] + "端口监听。");
		}
		// 要接收全部生成的key，并通过连接进行判断是否获取客户端的输出
		int keysAdd = 0;
		while ((keysAdd = selector.select()) > 0) { // 选择一组键，并且相应的通道已经准备就绪
			Set<SelectionKey> selectedKeys = selector.selectedKeys();// 取出全部生成的key
			Iterator<SelectionKey> iter = selectedKeys.iterator();
			while (iter.hasNext()) {
				SelectionKey key = iter.next(); // 取出每一个key
				if (key.isAcceptable()) {
					ServerSocketChannel server = (ServerSocketChannel) key.channel();
					SocketChannel client = server.accept(); // 接收新连接
					client.configureBlocking(false);// 配置为非阻塞
					ByteBuffer outBuf = ByteBuffer.allocateDirect(1024); //
					outBuf.put(("当前的时间为：" + new Date()).getBytes()); // 向缓冲区中设置内容
					outBuf.flip();
					client.write(outBuf); // 输出内容
					client.close(); // 关闭
				}
			}
			selectedKeys.clear(); // 清楚全部的key
		}

	}

}
